package userRgame

import (
	"VirtualCamera/common"
	"VirtualCamera/controllers"
	"VirtualCamera/models"
	"VirtualCamera/response"
	"fmt"
	_ "fmt"
	"strconv"
	"strings"
	_ "strings"
	//"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type UserRgameController struct {
	controllers.BaseController
}
// 流行热门游戏
func (con UserRgameController) GetPopuGames(c *gin.Context) {
	db := common.GetDB()
	var games []models.UserRgame
	find := db.Order("total desc").Select("game_id, sum(score) as total").Limit(50).Group("game_id").Find(&games)
	len := find.RowsAffected
	err := find.Error
	var resgame []models.Game
	var gameIds []uint
	var id uint
	for index := range games {
		id = games[index].GameID
		gameIds = append(gameIds,id)
	}
	db.Find(&resgame, gameIds)
	if err != nil{
		response.Response(c, http.StatusOK, 400, nil, "获取流行游戏失败")
	}
	ret := gin.H{
		"game":  resgame,
		"length": len,
	}
	response.Success(c, ret, "查询成功")
}
// 用户点赞加分
func (con UserRgameController) AddDianzanScore(c *gin.Context) {
	db := common.GetDB()
	var userRgame = models.UserRgame{}
	var userRgame1  = models.UserRgame{}
	var game models.Game
	c.Bind(&userRgame1)
	userId :=userRgame1.UserID
	gameId := userRgame1.GameID
	fmt.Print("userId",userId)
	fmt.Print("gameId",gameId)
	//fmt.Print("userId",score)
	//userRgame = models.UserRgame{UserID: uint(userId), GameID: uint(gameId), Score: float64(score)}
	// 根据userId和gameId查询是否之前用户已经打过分，判断islike是否为1，若为1说明点过赞此时减去5分，若为0此时加五分
	db.Where("user_id = ? AND game_id = ?", userId, gameId).First(&userRgame)
	db.First(&game,gameId)
	num := game.Likenum
	var user models.User
	db.First(&user, userId)
	interestedGames := user.InterestedGames
	// 如果没有打过分 则新建一条记录
	if userRgame.ID==0 {
		userRgame.UserID = uint(userId)
		userRgame.GameID = uint(gameId)
		userRgame.Islike = 1
		if interestedGames == ""{
			interestedGames += strconv.Itoa(int(gameId))
		}else{
			interestedGames += "," + strconv.Itoa(int(gameId))
		}
		num += 1
		userRgame.Score = 0
		userRgame.Score += 5.0
		db.Create(&userRgame)
	}else {
		if userRgame.Islike==1{
			interestedGamesArr :=strings.Split(interestedGames, `,`)
			fmt.Println("interestedGamesArr",interestedGamesArr)
			for key, value := range interestedGamesArr{
				value1,_ :=strconv.Atoi(value)
				if value1==int(gameId){
					interestedGamesArr =append(interestedGamesArr[:key], interestedGamesArr[key+1:]...)
					break
				}
			}
			interestedGames = strings.Join(interestedGamesArr, ",")
			num -= 1
			userRgame.Islike = 0
			userRgame.Score -= 3.0
		}else if userRgame.Islike==0{
			if interestedGames == ""{
				interestedGames += strconv.Itoa(int(gameId))
			}else{
				interestedGames += "," + strconv.Itoa(int(gameId))
			}
			num += 1
			userRgame.Islike = 1
			userRgame.Score += 5.0
		}
	}
	game.Likenum = num
	user.InterestedGames = interestedGames
	fmt.Println("likenum",game.Likenum)
	db.Save(&game)
	db.Save(&user)
	db.Save(&userRgame)
	response.Success(c, nil, "添加成功")
}
// 提交评论内容
func (con UserRgameController) AddComment(c *gin.Context) {
	db := common.GetDB()
	var userRgame1 = models.UserRgame{}
	var dataUserRgame  = models.UserRgame{}
	var game models.Game
	c.Bind(&userRgame1)
	userId := userRgame1.UserID
	gameId := userRgame1.GameID
	pinglun := userRgame1.Pinglun
    fmt.Println("userId",userId)
	fmt.Println("gameId",gameId)
	//查询数据库
	db.Where("user_id = ? AND game_id = ?",userId,gameId).First(&dataUserRgame)
	dataUserRgame.Pinglun = pinglun
	// 如果该用户没有评论/打分过，则新建一条记录
	if dataUserRgame.ID == 0 {
		dataUserRgame.UserID = userId
		dataUserRgame.GameID = gameId
		db.Create(&dataUserRgame)
	}else{
		db.Save(&dataUserRgame)
	}
	// 游戏评论人数加一
	db.First(&game,gameId)
	game.Cnum += 1
	db.Save(&game)
	// 返回用户的评价信息
	response.Success(c, nil, "添加成功")
}
// 获得当前游戏所有的评论列表
func (con UserRgameController) GetCommentList(c *gin.Context) {
	db := common.GetDB()
	//var userRgames []models.UserRgame
	//var userIds [] int
	//var comments [] string
	//var users [] models.User
	//var userNames [] string
	var userRCommons [] models.UserRComm
	// 获取请求的游戏id
	gameId := c.Query("gameId")
	// 获取请求的用户id
	//userId := c.Query("userId")
	// SELECT users.name, emails.email FROM `users` left join emails on emails.user_id = users.id
	//db.Model(&models.User{}).Select("users.name as userName,user_rgames.pinglun as comment").Joins("left join user_rgames on users.id = user_rgames.user_id").Where("user_rgames.game_id = ? AND user_rgames.pinglun <> ?",gameId,"").Scan(&userRCommons)
	db.Table("user_rgames").Select("users.name,user_rgames.pinglun").Joins("left join users on users.id = user_rgames.user_id").Where("user_rgames.game_id = ? AND user_rgames.pinglun <> ?",gameId,"").Scan(&userRCommons)
	//// 查询所有用户对该游戏的评价的记录
	//db.Where("game_id = ? AND pinglun <> ?",gameId,"").Find(&userRgames)
	//// 获取用户id列表和评价列表
	//for _,item := range userRgames {
	//	userIds = append(userIds,int(item.UserID))
	//	comments = append(comments,item.Pinglun)
	//}
	//// 根据用户id列表查询用户姓名
	//db.Find(&users,userIds)
	//for _,item := range users {
	//	userNames = append(userNames, item.Name)
	//}
	ret := gin.H{
		"commentList":userRCommons,
	}
	response.Success(c,ret,"获取评论列表成功")

}
// 添加收藏列表
func (con UserRgameController) AddCollectScore(c *gin.Context) {
	db := common.GetDB()
	var userRgame models.UserRgame
	var userRgame1 models.UserRgame
	var user models.User
	var game models.Game
	c.Bind(&userRgame)
	// 接收post参数
	userId := userRgame.UserID
	gameId := userRgame.GameID
	fmt.Print("userId",userId)
	fmt.Print("gameId",gameId)
	// 判断该用户是否对该游戏做过评价
	db.Where("user_id = ? and game_id = ?",userId,gameId).Find(&userRgame1)
	// 根据userId查询用户信息
	db.First(&user, userId)
	db.First(&game,gameId)
	num := game.Cnum
	// 若没有记录，则创建一条新纪录,且将iscollect置为1，并将游戏Id添加到用户收藏列表中
	if userRgame1.ID == 0 {
		userRgame.IsCollect = 1
		num += 1
		userRgame.Score += 10
		db.Create(&userRgame)
		// 在用户的收藏列表字符串末尾加上新收藏的游戏id
		if user.CollectedGames=="" {
			user.CollectedGames += strconv.Itoa(int(gameId))
		}else{
			user.CollectedGames += "," + strconv.Itoa(int(gameId))
		}
	} else {
		 /*如果没有收藏，则将iscollect置为1，且将该游戏加入到该用户的收藏列表中*/
        if userRgame1.IsCollect == 0 {
			userRgame1.IsCollect = 1
			num += 1
			userRgame1.Score += 10
			db.Save(&userRgame1)
			// 在用户的收藏列表字符串末尾加上新收藏的游戏id
			if user.CollectedGames=="" {
				user.CollectedGames += strconv.Itoa(int(gameId))
			}else{
				user.CollectedGames += "," + strconv.Itoa(int(gameId))
			}
		} else if userRgame1.IsCollect == 1{
			/* 如果用户已收藏，则需要将iscollect置为0，且将游戏id从用户的收藏列表中删除*/
			userRgame1.IsCollect = 0
			num -= 1
			userRgame1.Score -= 8
			db.Save(&userRgame1)
			// 将用户的游戏收藏列表字符串转换为数组
			collcetionArr := strings.Split(user.CollectedGames,",")
			// 遍历用户收藏的游戏列表
			for key,item := range collcetionArr {
				// 将字符串转换为int类型
				item1,_:= strconv.Atoi(item)
				fmt.Println("item1",item1)
				// 判断当前游戏Id是否是要删除的Id
				if uint(item1) == gameId{
					// 删除gameId
					fmt.Println(gameId)
					collcetionArr = append(collcetionArr[:key], collcetionArr[key+1:]...)
				}
				// 将数组拼接成字符串
				user.CollectedGames = strings.Join(collcetionArr,",")
			}
		}
	}
	// 保存用户信息的更新
	db.Save(&user)
	//game.Cnum = num
	db.Save(&game)
	response.Success(c, nil, "添加成功")
}
